<?php

namespace app\helpers;

use Exception;
use Yii;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\httpclient\Client;

class EmailHelper {

    const DAY_SEND_MAX = 200;

    protected static function generateEmailCode($email) {
        $code = md5($email . uniqid(time()));
        $key = "{$email}_code";
        Yii::$app->cache->set($key, $code, 3600 * 24);
        return $code;
    }

    public static function mailGun($email, $site, $username) {
        $url = 'https://api.mailgun.net/v3/mail.hahamh.net/messages';
        $code = self::generateEmailCode($email);
//        $activeUrl = Url::to(['auth/confirm', 'code' => $code]);
        $activeUrl = '';
        $data = [
            'site' => $site,
            'url' => $activeUrl,
            'username' => $username
        ];
        $param = [
            'from' => 'noreply@mail.hahamh.net',
            'to' => 'atcaoyufei@gmail.com',
            'subject' => "{$site} - 账号激活",
            'template' => 'verify_email',
            'h:X-Mailgun-Variables' => Json::encode($data)
        ];
        $auth = base64_encode('api:key-1a1snoeyn5hfeo8n823q10jdwyttr2u1');
        $client = new Client(['baseUrl' => $url]);
        try {
            $request = $client->createRequest()->setMethod('POST')
                ->setFormat(Client::FORMAT_URLENCODED)
                ->addHeaders(['Authorization' => "Basic {$auth}"]);
            $response = $request->addData($param)->send();
            return $response->data;
        } catch (Exception $e) {
            Yii::info($e->getMessage(), 'email');
        }
        return NULL;
    }

    public static function validate($email) {
        $key = "{$email}_code";
        $data = Yii::$app->cache->get($key);
        if (!$data) {
            return AppHelper::error("");
        }
        return AppHelper::success('');
    }

    public static function sendCode($email) {
        $day = date('Y-m-d');
        $key = "{$day}_available_send_count";
        $available_send_count = Yii::$app->cache->get($key);
        if (is_numeric($available_send_count) && $available_send_count <= 0) {
            return AppHelper::error('发信超过限制');
        }

        if (!$available_send_count) {
            $available_send_count = self::DAY_SEND_MAX;
        }

        $code = self::generateEmailCode($email);
        $res = self::sendCloud($email, $code);
        if (AppHelper::isOk($res)) {
            $duration = strtotime($day) + 86400 - 1 - time();
            $available_send_count -= 1;
            Yii::$app->cache->set($key, $available_send_count, $duration);
        }
        return $res;
    }

    protected static function sendCloud($email, $code) {
        $url = 'http://api.sendcloud.net/apiv2/mail/sendtemplate';
        $API_USER = 'hahamh_register';
        $API_KEY = '4BNB3E6TcyAAEn6O';
        $x_smtpapi = [
            'to' => [$email],
            'sub' => [
                '%code%' => [$code]
            ]
        ];
        $param = [
            'apiUser' => $API_USER,
            'apiKey' => $API_KEY,
            'from' => 'support@hahamh.net',
            'fromName' => 'support',
            'templateInvokeName' => 'hahamh_register_code',
            'xsmtpapi' => Json::encode($x_smtpapi),
        ];

        $data = http_build_query($param);
        $options = [
            'http' => [
                'method' => 'POST',
                'header' => 'Content-Type: application/x-www-form-urlencoded',
                'content' => $data,
                'timeout' => 10,
            ]];

        $context = stream_context_create($options);
        $result = file_get_contents($url, FALSE, $context);
        if (!is_array($result)) {
            $result = Json::decode($result);
        }
        return intval($result['statusCode']) === 200 ? AppHelper::success($result['info']) : AppHelper::error($result['message']);
    }
}